import Vue from "vue";
import Vuex from "vuex";
import { getMenuList } from "@/api";
import recursionRoutes from "@/utils/recursionRoutes";
import allRoutes from "@/router/allRoutes";

import dynamicRoutes from "../router/dynamicRoutes";

import router from "@/router";
Vue.use(Vuex);
//侧边菜单思路
//1.发送请求,获取用户菜单名
//2.通过递归函数计算出当前用户的路由配置
//3.将计算好的路由配置添加到 "/"路由的children中
export default new Vuex.Store({
  // strict: true,
  state: {
    //存储状态,那些被其它组件共享的数据都可以称之为state
    //vuex中的state和视图是一一对应的
    sideMenu: [],
    breadCrumb: [],
  },
  mutations: {
    //更改state的唯一方式?
    //一个type对应一个handle
    //mutation中的逻辑必须是同步的
    SET_SIDEMENU(state, payload) {
      state.sideMenu = payload;
      // console.log(state.sideMenu);
      //查找到dynamicRoutes中路径为"/"的这个对象,并且给它添加一个children属性,值就是就是那好的sideMenu
      let target = dynamicRoutes.find((item) => {
        return item.path === "/";
      });
      // console.log("===tar",target);
      // console.log("===pay",payload);
      target.children = state.sideMenu;

      //核心:通过addRoutes这个方法,动态的将路由配置添加到项目中
      router.addRoutes(dynamicRoutes);
    },
    //清空用户菜单
    CLEAR_SIDEMENU(state) {
      state.sideMenu = [];
    },
    //更改面包屑
    SET_BREADCRUMB(state, payload) {
      state.breadCrumb = payload;
    },
  },
  actions: {
    async FETCH_MENULIST({ commit }) {
      //发送请求获取用户菜单名
      let res = await getMenuList();
      //调用recursionRoutes 计算出用户路由配置
      if (res.data.state && res.data.menuList.length > 0) {
        let userMenu = recursionRoutes(res.data.menuList, allRoutes);
        commit("SET_SIDEMENU", userMenu);
      } else {
        //获取路由失败
      }
      //再提交给mutation
    },
  },
  modules: {},
  getters: {},
});
